// my-orders.ts
import { appointmentApi } from '../../utils/api'
Component({
  data: {
    currentTab: 'pending',
    orders: [],
    allOrders: []
  },

  lifetimes: {
    attached() {
      this.loadOrders()
    }
  },

  pageLifetimes: {
    show() {
      this.loadOrders()
    }
  },

  methods: {
    async loadOrders() {
      const res = await appointmentApi.getAppointmentList({
        status: this.data.currentTab
      })
      if(res.code == 200) {
        this.setData({
          orders: res.data,
          allOrders: res.data
        })
      }
    },

    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },

    getStatusText(status: string) {
      const statusMap: Record<string, string> = {
        pending: '待服务',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    },

    filterOrders(orders: any[], tab: string) {
      return orders.filter(order => order.status === tab)
    },

    switchTab(e: any) {
      const tab = e.currentTarget.dataset.tab
      this.setData({
        currentTab: tab,
        orders: this.filterOrders(this.data.allOrders, tab)
      })
    },

    cancelOrder(e: any) {
      const id = parseInt(e.currentTarget.dataset.id)

      try {
        wx.showModal({
          title: '确认取消',
          content: '确定要取消这个订单吗？',
          success: async (res) => {
            if (res.confirm) {
              const res = await appointmentApi.cancelAppointment(id)
              
              if(res.code == 200) {
                wx.showToast({
                  title: '已取消',
                  icon: 'success'
                })
              }
            }
          }
        })
      } catch (error) {
        console.log(error)
      }
      this.loadOrders()
    },

    goToReview(e: any) {
      const id = parseInt(e.currentTarget.dataset.id)
      wx.showToast({
        title: '评价功能开发中',
        icon: 'none'
      })
    }
  }
})